<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="计划名称" prop="name">
      <el-input v-model="dataForm.name" placeholder="计划名称"></el-input>
    </el-form-item>
    <el-form-item label="计划简介" prop="desc">
      <el-input v-model="dataForm.desc" placeholder="计划简介" type="textarea" :rows="4"></el-input>
    </el-form-item>
    <el-form-item label="计划目标" prop="goal">
      <el-input v-model="dataForm.goal" placeholder="计划目标"></el-input>
    </el-form-item>

    <el-form-item label="训练周期" prop="days">
      <el-input v-model="dataForm.days" placeholder="训练周期"></el-input>
    </el-form-item>
    <el-form-item label="每日训练时长" prop="trainLength">
      <el-input v-model="dataForm.trainLength" placeholder="每日训练时长"></el-input>
    </el-form-item>
    <el-form-item label="卡路里" prop="calorie">
      <el-input v-model="dataForm.calorie" placeholder="卡路里"></el-input>
    </el-form-item>

<!--   课程列表   -->
      <el-table ref="multipleTable" :data="allCourses" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
                style="width: 100%;">
        <el-table-column type="selection" header-align="center" align="center">
        </el-table-column>
        <el-table-column prop="id" label="课程ID" header-align="center" align="center" width="100">
        </el-table-column>
        <el-table-column prop="name" label="课程名称" width="570"></el-table-column>
      </el-table>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancelEdit">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        dataListLoading: false,
        dataListSelections: [],
        allCourses:[],
        dataForm: {
          id: 0,
          name: '',
          desc: '',
          goal: '',
          courses:[],
          // courses: {
          //   id:0,
          //   name:''
          // },
          // createTime: '',
          days: '',
          trainLength: '',
          calorie: ''
        },
        dataRule: {
          name: [
            { required: true, message: '计划名称不能为空', trigger: 'blur' }
          ],
          desc: [
            { required: true, message: '计划简介不能为空', trigger: 'blur' }
          ],
          goal: [
            { required: true, message: '计划目标不能为空', trigger: 'blur' }
          ],
          courseId: [
            { required: true, message: '课程id不能为空', trigger: 'blur' }
          ],
          createTime: [
            { required: true, message: '创建时间不能为空', trigger: 'blur' }
          ],
          days: [
            { required: true, message: '训练周期不能为空', trigger: 'blur' }
          ],
          trainLength: [
            { required: true, message: '每日训练时长不能为空', trigger: 'blur' }
          ],
          calorie: [
            { required: true, message: '卡路里不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      cancelEdit(){
        this.visible = false
        this.dataForm.id = 0
        this.dataForm.name = ''
        this.dataForm.desc = ''
        this.dataForm.goal = ''

        this.dataForm.courses = []
        this.dataForm.days = ''
        this.dataForm.trainLength = ''
        this.dataForm.calorie = ''
      },

      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
        // console.log(JSON.stringify(val))
      },
      init (row) {
        this.dataListLoading = true
        // this.dataForm.id = row || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
              if (row && row.id !== 0) {
                this.dataForm.id = row.id
                this.dataForm.name = row.name
                this.dataForm.desc = row.desc
                this.dataForm.goal = row.goal

                this.dataForm.courses = row.courses

                // this.dataListSelections = row.courses

                this.dataForm.days = row.days
                this.dataForm.trainLength = row.trainLength
                this.dataForm.calorie = row.calorie
              }

        })


        ////
        this.$http.get('/course/get-list').then(({
          data
        })=>{
          if (data && data.code === 200){
            this.allCourses = data.courses

            if (row){
              this.$nextTick(() => {
                if (row.courses){
                  // 遍历 row.courses 数组
                  row.courses.forEach(course => {
                    // 检查是否存在于 this.allCourses 中
                    const match = this.allCourses.find(item => item.id === course.id);

                    // 如果存在匹配项，选中行
                    if (match) {
                      const index = this.allCourses.indexOf(match);
                      this.$refs.multipleTable.toggleRowSelection(this.allCourses[index]);
                      // console.log("yes" + index)

                    }
                  });
                }
              });
            }

          }
        })



        setTimeout(()=>{
          // console.log(JSON.stringify(this.dataListSelections));
        },1000)

        this.dataListLoading = false;




      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.defaults.baseURL + `/plan/${this.dataForm.id ? 'updatePlanById' : 'insert'}`,
              method: 'post',
              data: {
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'desc': this.dataForm.desc,
                'goal': this.dataForm.goal,
                // 'courseId': this.dataForm.courseId,
                'courseId': this.dataListSelections.map(item => item.id),
                // 'createTime': this.dataForm.createTime,
                'days': this.dataForm.days,
                'trainLength': this.dataForm.trainLength,
                'calorie': this.dataForm.calorie
              }
            }).then(({data}) => {
              if (data && data.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
